package controllers

import (
	"github.com/astaxie/beego"
	"datapro/models"
	"HTdatapro/htmodels"
	"strconv"
	"time"
	"os"
	"strings"
	"github.com/astaxie/beego/validation"
)

type NodeController struct {
	beego.Controller
}

func (c *NodeController)Prepare() {
	c.Data["uname"] = c.GetSession("uname").(string)
	c.Data["uid"] = c.GetSession("uid").(int)
	c.Data["utype"] = c.GetSession("utype").(int)
}

//带了参数导致bootstrap table无法正常使用
func (c *NodeController)HTNodeList_html() {
	str_Type := c.Ctx.Input.URL()[strings.LastIndex(c.Ctx.Input.URL(), "/") + 1:]
	Type, _ := strconv.Atoi(str_Type)
	c.Data["Type"] = Type
	c.TplName = "node_list.html"
	c.Render()
}

func (c *NodeController)HTNodeList() {
	Type, _ := c.GetInt("Type")
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	fileds := []string{"Id", "Title", "UpdateTime", "Type"}
	Node := []models.Node{}
	htmodels.HTNodeGetList(&Node, fileds, Type, -1, offset, limit, search, "Title", orderby)
	count, _ := htmodels.HTNodeGetCount(search, "Title", Type, -1)
	c.Data["json"] = map[string]interface{}{"rows":&Node, "total":count}
	c.ServeJSON()
}

func (c *NodeController)HTNodeDetail() {
	Id, _ := c.GetInt64("Id")
	if Id != 0 {
		c.Data["update"] = true
		SetNodeDetailInfo(c, Id)
	}
	mytype, _ := c.GetInt("type")
	c.Data["Type"] = mytype
	c.TplName = "node_detail.html"
}

func SetNodeDetailInfo(c *NodeController, Id int64) {
	Node := models.Node{Id:int(Id)}
	htmodels.HTNodeGetDetail(&Node)
	c.Data["Node"] = &Node
}

func (c *NodeController)HTNodeAdd() {
	Node := models.Node{}
	if err := c.ParseForm(&Node); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	Node.CreatTime = time.Now()
	Node.UpdateTime = time.Now()
	valide := validation.Validation{}
	if b, err := valide.Valid(&Node); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTNodeAdd(&Node); err != nil {
		Message(&c.Controller, "", "添加失败，即将返回！" + err.Error(), "", true)
	}
	Message(&c.Controller, `/node/detail`, "添加成功！", "", false)
}

func (c *NodeController)HTNodeUpdate() {
	Id, _ := c.GetInt64("Id");
	Node := models.Node{Id:int(Id)}
	if err := htmodels.HTNodeGetDetail(&Node); err != nil {
		Message(&c.Controller, "", "严重错误，请联系管理员,即将返回！" + err.Error(), "", true)
	}
	if err := c.ParseForm(&Node); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("creattime")); err != nil {
		Node.CreatTime = time.Now()
	} else {
		Node.CreatTime = time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("updatetime")); err != nil {
		Node.UpdateTime = time.Now()
	} else {
		Node.UpdateTime = time_up
	}

	valide := validation.Validation{}
	if b, err := valide.Valid(&Node); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTNodeUpdate(&Node); err != nil {
		Message(&c.Controller, "", "更新失败，即将返回！" + err.Error(), "", true)
	}
	Message(&c.Controller, `/node/list_html` + `/` + strconv.Itoa(Node.Type), "更新成功！", "", false)
}

func (c *NodeController)HTNodeDelete() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	count, err := htmodels.HTNodeDelete(Ids)
	if err != nil {
		Json_Message(&c.Controller, 0, "删除失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "删除" + strconv.FormatInt(count, 10) + "行")
}


//multi doc image upload
func (c *NodeController)HTNodeMutiTextImageUp() {
	TacleUeditor(&c.Controller)
	_, h, err := c.GetFile("upfile")
	if err != nil {
		Json_Message(&c.Controller, 1, "file upload error")
	}
	date := time.Now().Format("2006-01-02")
	filename := RandString(8)
	typename := h.Filename[strings.LastIndex(h.Filename, "."):]
	path := beego.AppConfig.String("uploadspath")
	directory := "/node/mutitext/" + date
	totalFileName := path + directory + filename + typename
	url := "/uploads" + directory + filename + typename
	os.MkdirAll(path + directory, 0777)
	err = c.SaveToFile("upfile", totalFileName)
	if err != nil {
		Json_Message(&c.Controller, 1, "file save error" + err.Error())
	}
	c.Data["json"] = map[string]interface{}{"state": "SUCCESS", "url":  url, "name": filename + typename, "size":"1000", "originalName":  filename + typename, "type":typename}
	c.ServeJSON()
}

//HD

func (c *NodeController)HDGetNodePage() {
	Id, _ := c.GetInt64("Id");
	c.Data["Id"] = Id
	Node := models.Node{Id:int(Id)}
	htmodels.HTNodeGetDetail(&Node)
	c.Data["Node"] = &Node
	c.TplName = "hd/input.html"
}

func (c *NodeController)HDNodeUpdate() {
	Id, _ := c.GetInt64("Id");
	Node := models.Node{Id:int(Id)}
	if err := htmodels.HTNodeGetDetail(&Node); err != nil {
		Json_Message(&c.Controller, 1, "严重错误，请联系管理员,即将返回！" + err.Error())
	}
	if err := c.ParseForm(&Node); err != nil {
		Json_Message(&c.Controller, 1, "输入数据不对,即将返回！" + err.Error())
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("creattime")); err != nil {
		Node.CreatTime = time.Now()
	} else {
		Node.CreatTime = time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("updatetime")); err != nil {
		Node.UpdateTime = time.Now()
	} else {
		Node.UpdateTime = time_up
	}
	Node.EditorId = c.GetSession("uid").(int)
	if err := htmodels.HTNodeUpdate(&Node); err != nil {
		Json_Message(&c.Controller, 1, "更新失败，即将返回！" + err.Error())
	}
	Json_Message(&c.Controller, 0, "更新成功！")
}

func (c *NodeController)HDParentNodeListGetPage() {
	parentNode, _ := c.GetInt("FatherNode")
	CurrentNode := models.Node{Id:parentNode}
	htmodels.HTNodeGetDetail(&CurrentNode)
	Type := -1
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	fileds := []string{"Id", "Title", "UpdateTime", "Type", "CreatorId", "EditorId"}
	Node := []models.Node{}
	htmodels.HTNodeGetList(&Node, fileds, Type, parentNode, offset, limit, search, "Title", orderby)
	//count, _ := htmodels.HTNodeGetCount(search, "Title", Type, parentNode)
	c.Data["Node"] = &Node
	c.Data["CurrentNode"] = &CurrentNode
	c.TplName = "hd/list_parent.html"
}

func (c *NodeController)HDChildNodeListGetPage() {
	parentNode, _ := c.GetInt("FatherNode")
	CurrentNode := models.Node{Id:parentNode}
	htmodels.HTNodeGetDetail(&CurrentNode)

	Type := -1
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	fileds := []string{"Id", "Title", "UpdateTime", "Type", "CreatorId", "EditorId"}

	Node := []models.Node{}
	htmodels.HTNodeGetList(&Node, fileds, Type, parentNode, offset, limit, search, "Title", orderby)
	//count, _ := htmodels.HTNodeGetCount(search, "Title", Type, parentNode)
	c.Data["Node"] = &Node
	c.Data["CurrentNode"] = &CurrentNode
	c.TplName = "hd/list_child.html"
}

func (c *NodeController)HDNodeAdd() {
	Node := models.Node{}

	if err := c.ParseForm(&Node); err != nil {
		Json_Message(&c.Controller, 1, "输入数据不对,即将返回！" + err.Error())
	}
	Node.CreatTime = time.Now()
	Node.UpdateTime = time.Now()
	//valide := validation.Validation{}
	//if b, err := valide.Valid(&Node); !b || err != nil {
	//	if !b {
	//		Json_Message(&c.Controller, 1, "数据验证失败，即将返回！")
	//		Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
	//	}
	//	if err != nil {
	//		Json_Message(&c.Controller, 1, "数据验证错误，即将返回！" + err.Error())
	//	}
	//}
	Node.CreatorId = c.GetSession("uid").(int)
	//Node.EditorId = Node.CreatorId
	if err := htmodels.HTNodeAdd(&Node); err != nil {
		Json_Message(&c.Controller, 1, "添加失败，即将返回！" + err.Error())
	}
	Json_Message(&c.Controller, 0, "添加成功！")
}
